<?php
/**
 * 车商扣除透资保证金结算
 *
 * @author Xmh
 */
exit;
date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
if (isset($_SERVER['REQUEST_URI'])) {
    die('error');
}

if (!defined('API_ROOT_PATH')) {
    define('API_ROOT_PATH', dirname(__FILE__));
}

require(API_ROOT_PATH . '/../inc/common.php');
require(API_ROOT_PATH . '/../inc/Config.php');
require(API_ROOT_PATH . '/../inc/MysqliDb.php');

//初始化数据库链接
function init_db()
{
    $db = new MysqliDb ([
        'host' => MYSQLDB,
        'username' => MYSQLDB_USER,
        'password' => MYSQLDB_PWD,
        'db' => MYSQLDB_DATABASE,
        'port' => 3306,
        'prefix' => 'au_',
        'charset' => 'utf8'
    ]);
    return $db;
}

//初始化redis
function init_redis()
{
    $redis = new Redis();
    $redis->connect(REDIS_HOST, REDIS_PORT);
    return $redis;
}

/**
 * 获取月末最后一天
 *
 * @return false|string
 */
function getEndMonth()
{
    $BeginMonth = date('Y-m-01 H:i:s', strtotime(date("Y-m-d 23:59:00")));
    return date('Y-m-d H:i:s', strtotime("$BeginMonth +1 month -1 day"));
}


/**
 * 获取下次启动时间
 *
 * @return false|int
 */
function getNextSleepDays()
{
    $date1 = time();
    $date2 = getEndMonth();
    $date2 = strtotime($date2);
    $s = $date2 - $date1;

    $date1 = date('Y-m-d H:i:s', $date1);
    $date2 = date('Y-m-d H:i:s', $date2);

    print_r("currtime: $date1   nexttime: $date2   timediff: $s\n");

    return $s;
}

/**
 * 获取维保记录查询透支信用额度
 *
 * @return mixed
 */
function getRepairCreditLines()
{
    global $db;
    $RepairCreditLines = $db->where('name', 'REPAIR_CREDIT_LINES')->getOne('setting', 'value');
    return $RepairCreditLines['value'];
}

/**
 * 获取维保查询单条查询需要额度
 */
function getRepairSinglePrice()
{
    global $db;
    $RepairCreditLines = $db->where('name', 'REPAIR_SINGL_PRICE')->getOne('setting', 'value');
    return $RepairCreditLines['value'];
}

/**
 * 结算repair_pay_log
 *
 * @param  float $amount      结算金额
 * @param  int   $bail_log_id 保证金使用日志id
 * @param  int   $count       结算次数
 * @param  int   $dealer_id   车商id
 */
function the_bill($amount, $bail_log_id, $count, $dealer_id)
{
    global $db, $dbm;

    $result = $db->where('dealer_id', $dealer_id)->where('pay_state', 0)->where('search_state', 2)
        ->orderBy('createtime', 'ASC')->get('dealer_repair_log', null, 'createtime');

    $end = end($result);

    $first = reset($result);

    //查询次数
    $times = count($result);

    //多次结算
    if ($count) {
        $sql = "update au_dealer_repair_log set pay_state=1 where id in(select d.id from (select * from au_dealer_repair_log 
                where dealer_id=" . $dealer_id . "
			    and pay_state=0 and search_state=2 order by createtime desc LIMIT " . $count . ") as d )";
        $pay_state = $dbm->query($sql);
        $times = $count;
    } else {
        //全部结算
        $pay_state = $db->where('dealer_id', $dealer_id)->where('pay_state', 0)->where('search_state', 2)
            ->orderBy('createtime', 'ASC')->update('dealer_repair_log', ['pay_state' => 1]);
    }
    $option = array(
        'end_time' => $end['createtime'],
        'start_time' => $first['createtime'],
        'times' => $times,
        'dealer_id' => $dealer_id,
        'amount' => $amount,
        'bl_id' => $bail_log_id,
        'createtime' => date('Y-m-d H:i:s')
    );
    $bill_state = $db->insert('dealer_repair_pay_log', $option);
    if ($bill_state && $pay_state) {
        return true;
    } else {
        return false;
    }
}

$db = init_db();
$redis = init_redis();

$counter = 0;
//判断数据库链接状态
if (!$db->ping()) {
    $db = init_db();
}
$current_date = date("Y-m-d H:i:s");
$current_date_last = getEndMonth();
$repair_single_price = getRepairSinglePrice();
$list = $db->where('minus_amount', 0, '>')
    ->where('bail_amount', $repair_single_price, '>=')
    ->get('car_dealer', null, 'dealer_id,bail_amount,minus_amount');
$count_list = count($list);
logUtil("共" . $count_list . "条记录", 'INFO');
//当前时间大于月末最后一天指定时间执行
$diff_time = strtotime($current_date) - strtotime($current_date_last);
if ($diff_time >= 0) {
    while ($list) {
        $db->startTransaction();
        foreach ($list as $k => $v) {
            if ($v['bail_amount'] >= $repair_single_price) {
                $remain_minus_amount = $settlement_count = 0;
                $settlement_amount = $v['minus_amount'];
                $remain_bail_amount = $v['bail_amount'] - $v['minus_amount'];
                if ($v['bail_amount'] < $v['minus_amount']) {
                    //计算修改状态日志条数
                    $settlement_count = intval($v['bail_amount'] / $repair_single_price);        //结算次数
                    $settlement_amount = $settlement_count * $repair_single_price;        //结算金额
                    $remain_minus_amount = $v['minus_amount'] - $settlement_amount;       //剩余结算金额
                    $remain_bail_amount = intval(fmod(floatval($v['bail_amount']), $repair_single_price)); //剩余保证金金额
                }

                //更新保证金和清空透支金额
                $clear_state = $db->where('dealer_id', $v['dealer_id'])->update('car_dealer',
                    [
                        'bail_amount' => $remain_bail_amount,
                        'minus_amount' => $remain_minus_amount
                    ]
                );
                //添加保证金消费记录
                $bail_log_id = $db->insert('dealer_bail_log',
                    [
                        'dealer_id' => $v['dealer_id'],
                        'use_time' => $current_date,
                        'use_type' => 8,
                        'use_detail' => '车辆维保信息查询透资，金额扣除。',
                        'occur_money' => $settlement_amount,
                        'remain_amount' => $remain_bail_amount,
                        'createtime' => $current_date
                    ]
                );
                //结算扣除的维保透支金额次数
                $pay_state = the_bill($settlement_amount, $bail_log_id, $settlement_count, $v['dealer_id']);
                if ($clear_state > 0 && $bail_log_id > 0 && $pay_state) {
                    $db->commit();
                    logUtil("dealer_id: " . $v['dealer_id'] . "扣除维保透资金额：" . $settlement_amount . " 处理完成", 'INFO');
                    $counter++;
                    unset($list[$k]);
                } else {
                    $db->rollback();
                    logUtil("dealer_id: " . $v['dealer_id'] . "扣除维保透资金额：" . $settlement_amount . " 处理失败", 'INFO');
                    unset($list[$k]);
                }
            } else {
                logUtil("dealer_id: " . $v['dealer_id'] . "保证金余额不足，应扣除维保透资金额：" . $v['minus_amount'] . " 暂不处理", 'INFO');
                unset($list[$k]);
            }
        }
    } else {
        $sleepDays = getNextSleepDays();
        logUtil("Update repair amount will sleep:" . $sleepDays . ", 'INFO'");
        sleep($sleepDays);
    }
} else {
    $sleepDays = getNextSleepDays();
    logUtil("Update repair amount will sleep:" . $sleepDays . ", 'INFO'");
    sleep($sleepDays);
}
logUtil($counter . " 条数据处理完成", "INFO");
